package com.iagent.resovler.result;

import com.iagent.annotation.Order;
import com.iagent.exception.NotFoundResultResolverException;

/**
 * @auther liujieyu
 * @date 2022/12/2
 * @description 八大基本数据类型结果解析器,如果使用JSON适配器则效率较低，使用基本类型转换器效率50-100倍
 * @since 2.2.0
 */
@Order
public class BasicResultResolver extends AbstractResultResolver {
    @Override
    public boolean isResolver(Class<?> returnClass) {
        return int.class.isAssignableFrom(returnClass) || float.class.isAssignableFrom(returnClass) || double.class.isAssignableFrom(returnClass) || long.class.isAssignableFrom(returnClass) || byte.class.isAssignableFrom(returnClass) || char.class.isAssignableFrom(returnClass) || boolean.class.isAssignableFrom(returnClass) || short.class.isAssignableFrom(returnClass);
    }

    @Override
    public Object resolver(byte[] data, Class<?> returnClass) throws Throwable {
        String resultStr = new String(data);
        if (int.class.isAssignableFrom(returnClass)) {
            return Integer.parseInt(resultStr);
        } else if (float.class.isAssignableFrom(returnClass)) {
            return Float.parseFloat(resultStr);
        } else if (double.class.isAssignableFrom(returnClass)) {
            return Double.parseDouble(resultStr);
        } else if (long.class.isAssignableFrom(returnClass)) {
            return Long.parseLong(resultStr);
        } else if (byte.class.isAssignableFrom(returnClass)) {
            return Byte.parseByte(resultStr);
        } else if (char.class.isAssignableFrom(returnClass)) {
            // char类型取第二位， 第一位是 ""
            return resultStr.toCharArray()[1];
        } else if (boolean.class.isAssignableFrom(returnClass)) {
            return Boolean.parseBoolean(resultStr);
        } else if (short.class.isAssignableFrom(returnClass)) {
            return Short.parseShort(resultStr);
        } else {
            throw new NotFoundResultResolverException("Not Found Result Resolver");
        }
    }
}
